package com.ysd.lis.service.emr.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.dto.emr.EmrDto;
import com.ysd.lis.entity.emr.*;
import com.ysd.lis.mapper.emr.*;
import com.ysd.lis.request.emr.EmrParam;
import com.ysd.lis.service.emr.EmrItemStandardTaskService;
import com.ysd.util.ToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * cold_chain.sys_Model 服务实现类
 * </p>
 *
 * @author prs
 * @since 2024-12-27
 */
@Service
public class EmrItemStandardTaskServiceImpl extends ServiceImpl<EmrItemStandardTaskMapper, EmrItemStandardTask> implements EmrItemStandardTaskService {
    @Autowired
    EmrItemStandardTaskMapper emrItemStandardTaskMapper;
    @Autowired
    EmrItemStandardMapper emrItemStandardMapper;
    @Autowired
    EmrVersionMapper emrVersionMapper;
    @Autowired
    EmrVersionRoleMapper emrVersionRoleMapper;
    @Autowired
    EmrItemMapper emrItemMapper;
    @Override
    public Result findEmrItemStandardTree() {

        List<Map> returnList = new ArrayList<>();

        //先查询出所有的是lis系统得评价标准
        LambdaQueryWrapper<EmrItemStandard> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EmrItemStandard::getDelFlag, 0)
                .eq(EmrItemStandard::getIsLis, 1)
                .orderByAsc(EmrItemStandard::getSeq);
        List<EmrItemStandard> emrItemStandardList = emrItemStandardMapper.selectList(queryWrapper);
        //评价项目集合
        if(ToolsUtils.isNotEmpty(emrItemStandardList)){
            //循环评价标准 封装数据
            List<Map> sList = new ArrayList<>();
            for (EmrItemStandard emrItemStandard : emrItemStandardList) {
                Map<String,Object> map = new HashMap<>();
                map.put("id", emrItemStandard.getId());
                map.put("code", emrItemStandard.getStandardCode());
                map.put("name", emrItemStandard.getStandardCode()+emrItemStandard.getStandardName());
                map.put("standardCode", emrItemStandard.getStandardCode());
                map.put("versionCode", emrItemStandard.getVersionCode());
                map.put("roleCode", emrItemStandard.getRoleCode());
                map.put("itemCode", emrItemStandard.getItemCode());
                map.put("gradeCode", emrItemStandard.getGradeCode());
                map.put("type","emrItemStandard");
                sList.add(map);
            }

            //循环评价项目 封装数据
            List<Map> mList = new ArrayList<>();
            //根据itemCode（项目编号），（roleCode角色编号），versionCode（版本号）分组
            Map<List<Object>, List<EmrItemStandard>> standardListMap = emrItemStandardList.stream()
                    .collect(Collectors.groupingBy(s -> Arrays.asList(s.getItemCode(), s.getRoleCode(), s.getVersionCode())));
            for (List<Object> standardList : standardListMap.keySet()) {
                String itemCode = (String)standardList.get(0);
                String roleCode = (String)standardList.get(1);
                String versionCode = (String)standardList.get(2);
                LambdaQueryWrapper<EmrItem> queryWrapperI = new LambdaQueryWrapper<>();
                queryWrapperI.eq(EmrItem::getDelFlag, 0)
                        .eq(EmrItem::getItemCode, itemCode)
                        .eq(EmrItem::getRoleCode, roleCode)
                        .eq(EmrItem::getVersionCode, versionCode);
                List<EmrItem> emrItemList = emrItemMapper.selectList(queryWrapperI);
                if(ToolsUtils.isNotEmpty(emrItemList)){
                    for(EmrItem emrItem : emrItemList){
                        Map<String,Object> map = new HashMap<>();
                        map.put("id", emrItem.getId());
                        map.put("code", emrItem.getItemCode());
                        map.put("name", emrItem.getItemCode()+"-"+emrItem.getItemName());
                        map.put("versionCode", emrItem.getVersionCode());
                        map.put("roleCode", emrItem.getRoleCode());
                        map.put("children",sList.stream().filter(standard -> standard.get("itemCode").equals(emrItem.getItemCode())&&standard.get("roleCode").equals(emrItem.getRoleCode())&&standard.get("versionCode").equals(emrItem.getVersionCode())).collect(Collectors.toList()));
                        map.put("type","emrItem");
                        mList.add(map);
                    }
                }
            }

            //查角色数据
            List<String> roleCodeList = emrItemStandardList.stream().map(s -> s.getRoleCode()).distinct().collect(Collectors.toList());
            LambdaQueryWrapper<EmrVersionRole> queryWrapperR = new LambdaQueryWrapper<>();
            queryWrapperR.eq(EmrVersionRole::getDelFlag, 0)
                    .in(EmrVersionRole::getRoleCode, roleCodeList);
            List<EmrVersionRole> emrVersionRoleList = emrVersionRoleMapper.selectList(queryWrapperR);
            //循环角色数据 封装数据
            List<Map> rList = new ArrayList<>();
            if(ToolsUtils.isNotEmpty(emrVersionRoleList)){
                for (EmrVersionRole emrVersionRole : emrVersionRoleList) {
                    Map<String,Object> map = new HashMap<>();
                    map.put("id", emrVersionRole.getId());
                    map.put("code", emrVersionRole.getRoleCode());
                    map.put("name", emrVersionRole.getRoleCode()+"-"+emrVersionRole.getRoleName());
                    map.put("versionCode", emrVersionRole.getVersionCode());
                    map.put("children",mList.stream().filter(item -> item.get("roleCode").equals(emrVersionRole.getRoleCode())&&item.get("versionCode").equals(emrVersionRole.getVersionCode())).collect(Collectors.toList()));
                    map.put("type","emrVersionRole");
                    rList.add(map);
                }

            }

            //查一共多少版本数据
            List<String> vsCodeList = emrItemStandardList.stream().map(s -> s.getVersionCode()).distinct().collect(Collectors.toList());
            LambdaQueryWrapper<EmrVersion> queryWrapperv = new LambdaQueryWrapper<>();
            queryWrapperv.eq(EmrVersion::getDelFlag, 0)
                    .in(EmrVersion::getVersionCode, vsCodeList)
                    .orderByAsc(EmrVersion::getSeq);
            List<EmrVersion> emrVersionList = emrVersionMapper.selectList(queryWrapperv);
            //循环版本数据 封装数据
            if(ToolsUtils.isNotEmpty(emrVersionList)){
                for (EmrVersion emrVersion : emrVersionList) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", emrVersion.getId());
                    map.put("code", emrVersion.getVersionCode());
                    map.put("name", emrVersion.getVersionName());
                    map.put("type","emrVersion");
                    map.put("children",rList.stream().filter(item -> item.get("versionCode").equals(emrVersion.getVersionCode())).collect(Collectors.toList()));
                    returnList.add(map);
                }
            }
            return Result.succ(1, "查询成功", returnList);
        }
        return Result.succ(1, "查询成功", null);
    }

    @Override
    public Result findItemStandardTaskList(EmrParam pageParam) {
        MPJLambdaWrapper<EmrItemStandardTask> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(EmrItemStandardTask.class);
        lambdaQueryWrapper.eq(EmrItemStandardTask::getDelFlag, 0)
                .eq(EmrItemStandardTask::getVersionCode,pageParam.getVersionCode())
                .eq(EmrItemStandardTask::getRoleCode,pageParam.getRoleCode())
                .eq(EmrItemStandardTask::getItemCode,pageParam.getItemCode())
                .eq(EmrItemStandardTask::getStandardCode,pageParam.getStandardCode())
                .orderByAsc(EmrItemStandardTask::getSeq);
        List<EmrItemStandardTask> taskList = emrItemStandardTaskMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "查询成功", taskList);
    }

    @Override
    public Result addStandardTask(EmrItemStandardTask material) {
        int insert = emrItemStandardTaskMapper.insert(material);
        if (insert > 0) {
            return Result.succ(1, "添加成功", material);
        } else {
            return Result.fail(400, "添加失败", "");
        }
    }

    @Override
    public Result editStandardTask(EmrItemStandardTask material) {
        int updateById = emrItemStandardTaskMapper.updateById(material);
        if (updateById > 0) {
            return Result.succ(1, "提交成功", material);
        } else {
            return Result.fail(400, "修改失败", "");
        }
    }

    @Override
    public Result batchDeleteItemStandardTask(EmrDto dto) {
        List<EmrItemStandardTask> taskList = dto.getEmrItemStandardTaskList();
        List<String> ids = taskList.stream().map(EmrItemStandardTask::getId).collect(Collectors.toList());
        boolean b = this.removeByIds(ids);
        if (b) {
            return Result.succ(1, "删除成功", null);
        } else {
            return Result.fail(400, "删除失败", "");
        }
    }

}
